<template>
  <div class="mt-form"><slot></slot></div>
</template>

<script>
  const { schema } = require('../../utils/compile/validator')
  const objectPath = require('../../static/object-path')
  const formItemBehavior = require('../../behaviors/form-item.behavior')

  export default {
    relations: {
      formItemBehavior: {
        type: 'descendant', // 关联的目标节点应为子孙节点,
        target: formItemBehavior,
        linked: function (formItem) {
          // console.log('formItems', this.formItems, formItem)
          this.formItems[formItem.$id] = formItem
          if (this.descriptor) {
            let keys = Object.keys(this.descriptor)
            if (formItem.onSetDescriptor) {
              formItem.onSetDescriptor(keys, this.descriptor)
            }
          }
        },
        unlinked: function (formItem) {
          delete this.formItems[formItem.$id]
        }
      }
    },
    properties: {
      value: null,
    },
    observers: {
      // 'value': function (field) {
      //   console.log('field', field, this.data.value)
      //   this.setData({
      //     formValue: this.data.value ? this.data.value : {}
      //   })
      // }
    },
    created() {
      this.formItems = null
    },
    attached() {
      this.formItems = {}
      // console.log('attached')
    },
    pageLifetimes: {
      show() {
        console.log('pageLifetimes show', this.data.formValue)
      }
    },
    data() {
      return {
        descriptor: {},
        formValue: {},
      }
    },
    methods: {
      setValue(d) {
        console.log('form setValue', d)
        this.setData({
          formValue: d ? d : {}
        })
      },
      setDescriptor(d) {
        this.descriptor = d
        console.log('this.descriptor', this.descriptor)
        if (this.formItems) {
          let keys = Object.keys(d)
          for (let k in this.formItems) {
            if (this.formItems[k].onSetDescriptor) {
              this.formItems[k].onSetDescriptor(keys, d)
            }
          }
        }
      },
      validate(callback) {
        let keys = Object.keys(this.descriptor)
        if (keys.length > 0) {
          let validator = new schema(this.descriptor)
          validator.validate(this.data.formValue, callback)
        } else {
          callback()
        }
      },
      validateField(props, cb) {

      },
      mtFormChange(prop, val) {
        console.log('mtFormChange', prop, val)
        this.setData({
          [`formValue.${prop}`]: val
        }, () => {
          console.log(`mtFormChange ${prop}`, val, this.data.formValue)
          this.triggerEvent('change', prop, val, this.data.formValue)
        })
      },
      getValue() {
        return this.data.formValue
      },
      getParsedValue() {
        let d = JSON.parse(JSON.stringify(this.data.formValue))
        return d
      }
    }
  }
</script>
